<?php

require "../utility.php";

http_response_code(403);

function getRandomChar(): string {
    $rand = mt_rand(0, 64210) % 26;
    $base = rand(1011, 33313) % 2 == 1 ? 97 : 65;
    return chr($rand + $base);
}

function genRandomCode() {
    $first  = getRandomChar();
    $second = getRandomChar();
    $third  = getRandomChar();
    $fourth = getRandomChar();

    return $first.$second.$third.$fourth;
}

function storeCodeToDatabase(mysqli $conn, string $id, string $code): bool {
    $insert_str  = "INSERT INTO Codes (ID, raw) VALUES(?, ?) ON DUPLICATE KEY UPDATE raw = ?;";
    $insert_stmt = $conn->prepare($insert_str);
    $insert_stmt->bind_param("sss", $id, $code, $code);

    return $insert_stmt->execute();
}

if (check_keys($_GET, "ID")) {
    $id = $_GET["ID"];
    if (strlen($id) == 32) {
        $code = genRandomCode();
        $conn = connect_mysql();
        if (storeCodeToDatabase($conn, $id, $code)) {
            echo $code;
            http_response_code(200);
        }
        $conn->close();
    }
}

?>